package com.test.ayi.test.competablefuture;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.*;

public class CFtest7GetTimeout {
    // 让时间戳像弹幕一样飞
    private static final DateTimeFormatter TF = DateTimeFormatter.ofPattern("HH:mm:ss");

    public static void main(String[] args) {
        // 1. 点一份“慢吞吞”的外卖：需要 5 秒
        CompletableFuture<String> takeout = CompletableFuture.supplyAsync(() -> {
            log("外卖小哥出门取餐...");
            nap(5000);               // 假装路上堵车
            log("外卖到达！");
            return "🦐 麻辣小龙虾一份";
        });

        // 2. 我只等 3 秒，不来就退单
        try {
            log("我开始等外卖...");
            String food = takeout.get(3, TimeUnit.SECONDS); // ← 这就是超时的命门
            log("拿到外卖：" + food);
        } catch (TimeoutException e) {
            log("⚠️ 超时 3 秒，怒退单！");
        } catch (InterruptedException | ExecutionException e) {
            log("外卖翻车：" + e.getMessage());
        }

        // 3. 优雅地关掉线程池（防止厨师赖在厨房不走）
        ForkJoinPool.commonPool().awaitQuiescence(1, TimeUnit.SECONDS);
    }

    /* ---------- 工具方法 ---------- */
    private static void log(String msg) {
        System.out.printf("%s [%s] %s%n",
                LocalTime.now().format(TF),
                Thread.currentThread().getName(),
                msg);
    }

    private static void nap(long millis) {
        try { Thread.sleep(millis); } catch (InterruptedException ignored) {}
    }
}
